﻿using Cms.Core.Infrastructure.Extension;
using Cms.Core.Infrastructure.Filter;
using Cms.Core.Infrastructure.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cms.Core.Infrastructure.Dependency
{
    public class DependencyTypeFinder : FinderBase<Type>,IDependencyTypeFinder
    {
        private IAllAssemblyFinder AllAssemblyFinder { get; set; }

        public DependencyTypeFinder()
        {
            AllAssemblyFinder = new Cms.Core.Infrastructure.Helps.RuntimeHelper();
        }

        /// 重写以实现所有项的查找
        /// </summary>
        /// <returns></returns>
        protected override Type[] FindAllItems()
        {
            Type[] baseTypes = new[] { typeof(ISingletonDependency), typeof(IScopeDependency), typeof(ITransientDependency) };
            Type[] types = AllAssemblyFinder.FindAll(fromCache: true).SelectMany(assembly => assembly.GetTypes())
                .Where(type => type.IsClass && !type.IsAbstract && !type.IsInterface && !type.HasAttribute<IgnoreDependencyAttribute>()
                    && (baseTypes.Any(b => b.IsAssignableFrom(type)) || type.HasAttribute<DependencyAttribute>())).ToArray();
            
            return types;
        }
    }
}
